package com.znufe.exam.controller.student;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.github.pagehelper.PageInfo;
import com.znufe.exam.base.BaseApiController;
import com.znufe.exam.domain.*;
import com.znufe.exam.domain.course.CourseDirectoryObject;
import com.znufe.exam.domain.course.CoursePageResponseObject;
import com.znufe.exam.domain.course.CourseResponseObject;
import com.znufe.exam.domain.lecturer.LecturerResponseObject;
import com.znufe.exam.service.*;
import com.znufe.exam.utility.PageInfoHelper;
import com.znufe.exam.viewmodel.admin.course.CoursePageResponseVm;
import com.znufe.exam.viewmodel.student.course.CourseSearchResponseVm;
import com.znufe.exam.viewmodel.student.course.*;
import com.znufe.exam.viewmodel.student.lecturer.LecturerResponseVm;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

import com.znufe.exam.base.RestResponse;
import com.znufe.exam.base.SystemCode;

/**   
 * 
 * @Description:  课程表接口层
 * @Author:       gong   
 * @CreateDate:   Course
 * @Version:      V1.0
 *    
 */
@Api(description="课程信息接口")
@RestController("UserCourseController")
@RequestMapping("/api/user/course")
@AllArgsConstructor
public class CourseController extends BaseApiController {


	private final CourseService courseService;
	private final LecturerService lecturerService;
	private final SubCourseService subCourseService;
	private final CourseSubCourseService courseSubCourseService;
	private final CourseExamPaperService courseExamPaperService;
	private final ExamPaperService examPaperService;
	private final CategoryService categoryService;
	private final CourseStudentClassService courseStudentClassService;
	
	/**
	 * @explain 查询课程表对象  <swagger GET请求>
	 * @param   id
	 * @return  course
	 * @author  gong
	 * @time    Course
	 */
	@GetMapping("/getCourseById/{id}")
	@ApiOperation(value = "根据课程ID获取课程信息", notes = "传入课程ID")
	@ApiImplicitParam(paramType="path", name = "id", value = "课程id", required = true, dataType = "int")
	public RestResponse<Course> getCourseById(@PathVariable("id")Integer id){
		try {
			Course course=courseService.selectByPrimaryKey(id);
			if (course!=null) {
				return RestResponse.ok(course);
			} else {
				return RestResponse.fail(SystemCode.NoDataExist.getCode(),SystemCode.NoDataExist.getMessage());
			}
		} catch (Exception e) {
			return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
		}
	}

	@GetMapping("/getCourseDirectory/{id}")
    @ApiOperation(value = "根据课程ID获取课程目录",notes = "传入课程ID")
    public RestResponse getCourseDirectory(@PathVariable("id")Integer id){
        List<CourseDirectoryObject> courseOutlineList = courseService.getCourseDirectoryById(id);
        return RestResponse.ok(courseOutlineList);
    }

    @PostMapping("/bindStudentClass")
    @ApiOperation(value = "绑定课程和班级",notes = "参数为课程ID和班级ID")
    public RestResponse bindStudentClass(@RequestBody CourseClassRequestVm requestVm){
	    CourseStudentClass courseStudentClass = courseStudentClassService.selectByCourseClassId(requestVm.getCourseId(),
                requestVm.getClassId());
	    if (null != courseStudentClass){
	        return RestResponse.ok(courseStudentClass);
        }else {
            CourseStudentClass csc = new CourseStudentClass();
            csc.setClassId(requestVm.getClassId());
            csc.setCourseId(requestVm.getCourseId());
            csc.setGmtCreate(new Date());
            int reg = courseStudentClassService.insertSelective(csc);
            if (reg > 0){
                return RestResponse.ok(csc);
            }else {
                return RestResponse.fail(SystemCode.InsertDataFail.getCode(),SystemCode.InsertDataFail.getMessage());
            }
        }
    }

    @PostMapping("/queryCourseByProject")
    @ApiOperation(value = "安全培训页面分级别展示课程", notes = "参数是课程的项目分类和排序参数")
    public RestResponse<List<CourseDisplayVm>> queryCourseByProject(@RequestBody CourseProjectRequestVm requestVm) {
        ArrayList<CourseDisplayVm> course = new ArrayList<>();
        List<Category> typeList = categoryService.getAllType();
        Integer courseProject = requestVm.getCourseProject();
        String orderByField = requestVm.getOrderByField();
        for (int i = 0; i < typeList.size(); i++) {
            List<Course> courseList = courseService.queryCourseByProjectAndType(courseProject,typeList.get(i).getId(),orderByField);
            List<CourseResponseVm> courseResponseVmList = courseList.stream().map(d -> {
                CourseResponseVm vm = modelMapper.map(d, CourseResponseVm.class);
                return vm;
            }).collect(Collectors.toList());
            CourseDisplayVm courseDisplayVm = new CourseDisplayVm();
            courseDisplayVm.setTypeId(typeList.get(i).getId());
            courseDisplayVm.setName(typeList.get(i).getConcreteName());
            courseDisplayVm.setValue(courseResponseVmList);
            course.add(courseDisplayVm);
        }
        return RestResponse.ok(course);
    }

    /**
     * @explain 按级别和名称搜索课程
     * @param requestVm
     * @return
     */
    @PostMapping("/queryCourseByTypeAndName")
    @ApiOperation(value = "按级别和名称搜索课程", notes = "级别若是全部则为null，课程名称可以设定默认值")
    public RestResponse<PageInfo<CourseSearchResponseVm>> queryCourseByTypeAndName(@RequestBody CourseSearchRequestVm requestVm){
        requestVm.setCourseName(requestVm.getCourseName().trim());
        PageInfo<Course> courseList = courseService.queryCourseByTypeAndName(requestVm);
        PageInfo<CourseSearchResponseVm> coursePage = PageInfoHelper.copyMap(courseList,d->CourseSearchResponseVm.from(d));
        return RestResponse.ok(coursePage);
    }

    /**
     * @explain 按级别查看更多课程(分页)
     * @param requestVm
     * @return
     */
    @RequestMapping(value = "/viewMoreCourse",method = RequestMethod.POST,produces = "application/json")
    @ApiOperation(value = "按级别查看更多课程", notes = "结果分页")
    @ApiImplicitParam(paramType="body", name = "requestVm", value = "课程级别和分页参数", dataType = "CoursePageRequestVm",required = true)
    public RestResponse<PageInfo<CourseResponseVm>> viewMoreCourse(@RequestBody CoursePageRequestVm requestVm){
        requestVm.setCourseName(requestVm.getCourseName().trim());
        PageInfo<Course> pageInfo = courseService.getCoursePageByType(requestVm);
        PageInfo<CourseResponseVm> page = PageInfoHelper.copyMap(pageInfo,d->CourseResponseVm.from(d));
        return RestResponse.ok(page);
    }

    /**
     * @explain 显示课程概述：课程信息+讲师信息
     * @param requestVm
     * @return
     */
    @RequestMapping(value = "/courseOverview",method = RequestMethod.POST,produces = "application/json")
    @ApiOperation(value = "显示课程概述：课程信息+讲师信息", notes = "参数是课程ID")
    public RestResponse<CourseOverviewVm> courseOverview(@RequestBody CourseIdRequestVm requestVm){
        CourseOverviewVm courseOverviewVm = new CourseOverviewVm();
        try {
            Course course = courseService.selectByPrimaryKey(requestVm.getCourseId());
            if(course != null){
                CourseResponseVm courseResponseVm = CourseResponseVm.from(course);
                courseOverviewVm.setCourseResponseVm(courseResponseVm);
                List<Integer> subCourseId = courseSubCourseService.getAllSubCourseId(requestVm.getCourseId());
                if(subCourseId.size() == 0){
                    courseOverviewVm.setLecturerResponseVmList(Collections.emptyList());
                    return RestResponse.ok(courseOverviewVm);
                }
                List<Integer> lecturerId = subCourseService.getAllLecturerId(subCourseId);
                List<LecturerResponseObject> lecturerList = lecturerService.getLecturerListById(lecturerId);
                courseOverviewVm.setLecturerResponseVmList(lecturerList);
                return RestResponse.ok(courseOverviewVm);
            }else {
                return RestResponse.fail(SystemCode.NoDataExist.getCode(),SystemCode.NoDataExist.getMessage());
            }
        }catch (Exception e) {
            return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
        }
    }

    /**
     * @explain 显示课程大纲
     * @param requestVm
     * @return
     */
    @RequestMapping(value = "/courseOutline",method = RequestMethod.POST,produces = "application/json")
    @ApiOperation(value = "显示课程大纲", notes = "参数是课程ID")
    public RestResponse courseOutline(@RequestBody CourseIdRequestVm requestVm){
        List<CourseResponseObject> courseOutlineList = courseService.getCourseOutlineById(requestVm.getCourseId());
        return RestResponse.ok(courseOutlineList);
    }

    @RequestMapping(value = "/courseTest",method = RequestMethod.POST,produces = "application/json")
    @ApiOperation(value = "显示测试考核，显示正式考试试卷",notes = "参数是课程ID")
    public RestResponse<List<ExamPaper>> courseTest(@RequestBody CourseIdRequestVm requestVm){
        List<Integer> examPaperId = courseExamPaperService.getAllExamPaperId(requestVm.getCourseId());
        if(examPaperId.size() == 0){
            return RestResponse.ok(Collections.emptyList());
        }else {
            List<ExamPaper> paperList = examPaperService.getExamPaperListById(examPaperId);
            return RestResponse.ok(paperList);
        }
    }

    @RequestMapping(value = "/coursePage",method = RequestMethod.POST)
    @ApiOperation(value = "分页显示课程信息+搜索")
    public RestResponse<PageInfo<CoursePageResponseVm>> courseList(@RequestBody CoursePageRequestVm requestVM){
        try {
            requestVM.setCourseName(requestVM.getCourseName().trim());
            PageInfo<CoursePageResponseObject> pageInfo = courseService.coursePage(requestVM);
            PageInfo<CoursePageResponseVm> page = PageInfoHelper.copyMap(pageInfo, d -> CoursePageResponseVm.from(d));
            return RestResponse.ok(page);
        }catch (Exception e){
            return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
        }
    }
}